package com.itfreer.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * 定义属性文件
 * 
 * @author chenxu
 * 
 */
public class PropertiesUtils {

	private static Properties file = new Properties();
	private String fileName;

	/**
	 * 初始化文件
	 * 
	 * @param fileName
	 */
	public void iniFile(String fileName) {
		this.fileName = fileName;
		InputStream inputStream = getClass()
				.getResourceAsStream("/" + fileName);
		if (inputStream == null) {
			System.out.println(fileName + "不能为空!");
		} else {
			try {
				file.load(inputStream);
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		}
	}

	/**
	 * 读取文件
	 */
	public String read(String propertyName) {
		return file.getProperty(propertyName);
	}

	/**
	 * 写文件
	 */
	public void write(String name, String value) {
		file.setProperty(name, value);
	}

	/**
	 * 保存文件
	 */
	public void save() {
		try {
			OutputStream os = new FileOutputStream(fileName);
			file.store(os, null);
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
}
